<?php
/**
 * Album Controller
 *
 * @author hiscaler <hiscaler@gmail.com>
 * @link http://www.yuandot.com/
 * @copyright Copyright &copy; 2009-2010 Yuandot Information Technology CO.,LTD.
 * @license http://doit.yuandot.com/license/
 */

class AlbumsController extends Controller {
    public $layout = 'contents';
    const PAGE_SIZE = 12;

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
//            array('allow',  // allow all users to perform 'index' and 'view' actions
//                'actions' => array('index', 'view'),
//                'users' => array('*'),
//            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array(
                    'index', 'create', 'update', 'view', 'changeStatus', 'changeRecommend',
                    'changePicking', 'removePicture', 'setCover'
                ),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'batchProcess'),
                'users' => array('admin'),
            ),
            array('deny',  // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     */
    public function actionView() {
        $album = $this->loadModel();
        $pid = Yii::app()->request->getParam('pid', 0);
        $picture = AlbumPicture::model()->find("album_id = {$album->id} AND id = {$pid}");
        if ($picture === null) {
            $picture = $this->newPicture($album);
        } else {
            $picture = $this->updatePicture($album, $pid);
        }

        $this->render('view', array(
            'album' => $album,
            'picture' => $picture,
        ));
    }

    // 增加相册照片
    protected function newPicture($album) {
        $picuture = new AlbumPicture();
        if (isset($_POST['AlbumPicture'])) {
            $picuture->attributes = $_POST['AlbumPicture'];
            if ($album->addPicture($picuture)) {
                Album::model()->updateCounters(array('pictures_count' => 1), "id = {$album->id}");
                Yii::app()->user->setFlash('add_picture_success', Yii::t('album', 'add_picture_success'));
                $this->refresh();
            }
        }
        return $picuture;
    }

    // 更新相册照片
    protected function updatePicture($album, $picture_id) {
        $picuture = AlbumPicture::model()->find("album_id = {$album->id} AND id = {$picture_id}");
        if (isset($_POST['AlbumPicture'])) {
            $picuture->attributes = $_POST['AlbumPicture'];
            if ($album->addPicture($picuture)) {
                Yii::app()->user->setFlash('update_picture_success', Yii::t('album', 'update_picture_success'));
                $this->refresh();
            }
        }
        return $picuture;
    }

    // 删除相册图片
    public function actionRemovePicture() {
        if (Yii::app()->request->isAjaxRequest) {
           $pid = Yii::app()->request->getParam('pid');
           $picture = AlbumPicture::model()->findByPk($pid);
           if ($picture === null) {
               throw new CHttpException(404, 'The requested page does not exist.');
           } else {
               $picture->delete();
               Album::model()->updateCounters(array('pictures_count' => -1), "id = {$picture->album_id}");
               Album::model()->updateAll(array('cover_picture_id' => 0), "cover_picture_id = {$pid}");
           }
        }
    }
    
    // 设置相册封面
    public function actionSetCover() {
        if (Yii::app()->request->isAjaxRequest) {
           $aid = Yii::app()->request->getParam('aid');
           $pid = Yii::app()->request->getParam('pid');
           $album = Album::model()->findByPk($aid);
           $picture = AlbumPicture::model()->findByPk($pid);
           if (($album === null) || ($picture === null)) {
               throw new CHttpException(404, 'The requested page does not exist.');
           } else {
               $c = Album::model()->updateByPk($album->id, array('cover_picture_id' => $picture->id));
               if ($c) {
                   echo $picture->pictureSourcePath;
               }
           }
        }
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Album;
        $model->node_id = Yii::app()->request->getParam('node');
        if (isset($_POST['Album'])) {
            $model->attributes = $_POST['Album'];
            if ($model->save()) {
                $this->redirect(array('view', 'id' => $model->id));
            }
        }

        $this->render('edit', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     */
    public function actionUpdate() {
        $model = $this->loadModel();
        if (isset($_POST['Album'])) {
            $model->attributes = $_POST['Album'];
            if ($model->save()) {
                $this->redirect(array('view', 'id' => $model->id));
            }
        }

        $this->render('edit', array(
            'model' => $model,
        ));
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $current_node = Yii::app()->request->getParam('node');
        $criteria = new CDbCriteria;
        $criteria->condition = 'status != ' . Options::STATUS_PENDING_DELETE;
        if (intval($current_node)) {
            $criteria->addCondition("node_id = {$current_node}");
        }

        $pages = new CPagination(Album::model()->count($criteria));
        $pages->pageSize = self::PAGE_SIZE;
        $pages->applyLimit($criteria);

        $sort = new CSort('Album');
        $sort->applyOrder($criteria);

        $models = Album::model()->findAll($criteria);

        $this->render('index',array(
            'models' => $models,
            'pages' => $pages,
            'sort' => $sort,
            'current_node' => $current_node,
        ));
    }

    // change status
    public function actionChangeStatus() {
        if (Yii::app()->request->isAjaxRequest) {
            $id = Yii::app()->request->getPost('id');
            $model = Album::model()->findByPk($id);
            switch ($model->status) {
                case Options::STATUS_DRAFT:
                    $status = Options::STATUS_PUBLISHED;
                    break;
                case Options::STATUS_PUBLISHED:
                    $status = Options::STATUS_DRAFT;
                    break;
            }
            $model->status = $status;
            try {
                $model->save(false);
//                print_r($model->getErrors());
            } catch (Exception $ex) {
                echo $ex;
            }

            echo $model->statusIconFormat;
        }
    }

    /**
     * change "is_recommend" value, false or true
     */
    public function actionChangeRecommend() {
        if (Yii::app()->request->isAjaxRequest) {
            $id = Yii::app()->request->getPost('id');
            $model = Album::model()->findByPk($id);
            $value = (intval($model->is_recommend))
                ? Options::RECOMMEND_NO
                : Options::RECOMMEND_YES;
            $model->is_recommend = $value;
            try {
                $model->save(false);
            } catch (Exception $ex) {
                echo $ex;
            }

            echo $model->isRecommendIconFormat;
        }
    }

    /*
     * change "is_picking" value, false or true
     */
    public function actionChangePicking() {
        if (Yii::app()->request->isAjaxRequest) {
            $id = Yii::app()->request->getPost('id');
            $model = Album::model()->findByPk($id);
            $value = (intval($model->is_picking))
                ? Options::PICKING_NO
                : Options::PICKING_YES;
            $model->is_picking = $value;
            try {
                $model->save(false);
            } catch (Exception $ex) {
                echo $ex;
            }

            echo $model->isPickingIconFormat;
        }
    }

    // 批量更新
    public function actionBatchProcess() {
        if (Yii::app()->request->isPostRequest) {
            $action = strtolower(trim(Yii::app()->request->getPost('action_list')));
            switch ($action) {
                case 'update_order_pos':
                    $order_pos = Yii::app()->request->getPost('order_pos');
                    if (!empty($order_pos)) {
                        foreach ($order_pos as $key => $value) {
                            Album::model()->updateByPk($key, array('order_pos' => $value));
                        }
                    }
                    break;
                case 'delete_selected':
                    $select = Yii::app()->request->getPost('select');
                    if (!empty($select)) {
                        foreach ($select as $id) {
                            $model = Album::model()->findByPk($id)->delete();
                        }
                    }
                    break;
                case 'move_to_recycle_bin':
                    $select = Yii::app()->request->getPost('select');
                    if (!empty($select)) {
                        foreach ($select as $id) {
                            $model = Album::model()->updateByPk($id, array(
                                'status' => Options::STATUS_PENDING_DELETE));
                        }
                    }
                    break;
            }

            $this->redirect(array('index', 'node' => Yii::app()->request->getPost('current_node')));
        } else {
            throw new CHttpException(400, Yii::t('common', 'invalid_request'));
        }
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     */
    public function loadModel() {
        if($this->_model===null) {
            if(isset($_GET['id']))
                $this->_model=Album::model()->findbyPk($_GET['id']);
            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        }
        return $this->_model;
    }
}
